package com.ruoyi.common.utils.file;

import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.DecimalFormat;

public class FileAttachmentUtils {


    public static void createResizedImage(File sourceFile, File destFile, int width, int height, float quality) throws IOException {
        BufferedImage image = ImageIO.read(sourceFile);
        Dimension dimension = new Dimension(width, height);
        if(image.getHeight() == dimension.height && image.getWidth() == dimension.width) {
            writeUntouchedImage(sourceFile, destFile);
        } else {
            resizeImage(image, dimension.width, dimension.height, quality, destFile);
        }

    }

    private static void resizeImage(BufferedImage sourceImage, int width, int height, float quality, File destFile) throws IOException {
        try {
            Thumbnails.of(new BufferedImage[]{sourceImage}).size(width, height).keepAspectRatio(true).outputQuality(quality).toFile(destFile);
        } catch (IllegalStateException var6) {
            Thumbnails.of(new BufferedImage[]{sourceImage}).size(width, height).keepAspectRatio(true).toFile(destFile);
        }

    }


    private static void writeUntouchedImage(File sourceFile, File destFile) throws IOException {
        FileInputStream fileIS = new FileInputStream(sourceFile);
        writeUntouchedImage((InputStream)fileIS, destFile);
    }

    private static void writeUntouchedImage(InputStream stream, File destFile) throws IOException {
        ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
//        boolean readNum = true;

        int readNum1;
        while((readNum1 = stream.read(buffer)) != -1) {
            byteArrayOS.write(buffer, 0, readNum1);
        }

        byte[] bytes = byteArrayOS.toByteArray();
        byteArrayOS.close();
        FileOutputStream fileOS = new FileOutputStream(destFile);
        fileOS.write(bytes);
        fileOS.flush();
        fileOS.close();
    }


	 /**
     * 转换文件大小
     */
    public static String formatFileSize(long size) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (size == 0) {
            return wrongSize;
        }
        if (size < 1024) {
            fileSizeString = df.format((double) size) + "B";
        } else if (size < 1048576) {
            fileSizeString = df.format((double) size / 1024) + "KB";
        } else if (size < 1073741824) {
            fileSizeString = df.format((double) size / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) size / 1073741824) + "GB";
        }
        return fileSizeString;
    }

}
